package com.umpay.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;


/**
 * ***********************************************************************
 * <br>description : DES加密类
 * @author      xiatian
 * @date        Oct 16, 2012 11:12:48 AM
 * @version     1.0  
 * @see         HashSignHelper.java                 
 ************************************************************************
 */
public class HashEncrypt {

	private static final char[] DIGITS = { '0', '1', '2', '3', '4', '5', '6',
			'7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

	/**
	 * <br>description : 加密处理方法
	 * @param text
	 * @param algorithm
	 * @param inputCharset
	 * @return
	 * @author      xiatian
	 * @version     1.0
	 * @date        Oct 16, 201211:13:37 AM
	 */
	public static String doEncrypt(String text, String algorithm, String inputCharset) {
		MessageDigest msgDigest = null;

		try {
			msgDigest = MessageDigest.getInstance(algorithm);
		} catch (NoSuchAlgorithmException e) {
			throw new IllegalStateException(
					"System doesn't support this algorithm.");
		}

		try {
			msgDigest.update(text.getBytes(inputCharset)); 
		} catch (UnsupportedEncodingException e) {
			throw new IllegalStateException(
					"System doesn't support your  EncodingException.");
		}

		byte[] bytes = msgDigest.digest();

		String md5Str = new String(encodeHex(bytes));

		return md5Str;
	}
	
	
	public static char[] encodeHex(byte[] data) {

		int l = data.length;
		char[] out = new char[l << 1];
		for (int i = 0, j = 0; i < l; i++) {
			out[j++] = DIGITS[(0xF0 & data[i]) >>> 4];
			out[j++] = DIGITS[0x0F & data[i]];
		}
		return out;
	}
	
}